package com.l.web.master.system.group;

import com.l.web.master.system.user.User;
import com.l.web.master.system.user.UserDAO;
import org.l.qiao.Cluster;
import org.l.qiao.LConstant;
import org.l.qiao.Page;
import org.l.qiao.search.Field;
import org.l.qiao.search.Query;
import org.l.qiao.web.KeyUpdate;
import org.l.qiao.web.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GroupService {
    @Autowired
    private GroupDAO groupDAO;
    @Autowired
    private UserDAO userDAO;

    public GroupService() {
    }

    public Cluster getPageList(Page page) {
        Field field = new Field();
        Query query = new Query();
        field.include(Group.NAME, Group.CREATED);
        Cluster groupPage = groupDAO.findPage(query, field, null, page);
        List<Map<String, Object>> list = (List<Map<String, Object>>) groupPage.get(LConstant.PAGE_LIST);
        return groupPage;
    }

    public Group getDetail(String id) {
        Cluster cluster = groupDAO.findById(id);
        return new Group(cluster);
    }

    public List<Cluster> getGroupUser(String groupId) {
        Query query = new Query();
        query.eq(User.GROUP_ID, groupId);
        List<Cluster> users = userDAO.find(query, null, null);
        return users;
    }

    public int save(Group group) {
        String id = group.setId();
        group.put(Group.CREATED, new Date());
        groupDAO.insert(group);
        return ResponseCode.FINISH;
    }

    public int update(KeyUpdate keyUpdate) throws Exception {
        groupDAO.update(keyUpdate);
        return ResponseCode.FINISH;
    }

    public int remove(List<String> ids) {
        Query query = new Query();
        query.idIn(ids);
        groupDAO.remove(query);
        return ResponseCode.FINISH;
    }
}
